<template>
  <div class="schedule_box" v-loading="loading">
    <div class="schedule_addbtn">
      <el-button icon="plus" @click="openAddDialog()" type="primary">
        新增安排
      </el-button>
    </div>
    <el-table
      :data="scheduleDatas"
      border
      :header-row-style="{ color: '#232324', fontWeight: 'bold' }"
    >
      <el-table-column
        align="center"
        type="index"
        :index="indexMethod"
        label="序号"
        width="80"
      />
      <el-table-column
        align="center"
        label="课程名称"
        min-width="120"
        prop="courseName"
      />
      <el-table-column
        align="center"
        label="老师"
        min-width="120"
        prop="teacher.name"
      />
      <el-table-column
        align="center"
        label="教室"
        min-width="120"
        prop="classroom"
      />
      <el-table-column
        align="center"
        label="描述"
        min-width="180"
        prop="description"
      />
      <el-table-column
        align="center"
        label="次数"
        min-width="120"
        prop="lessonNumber"
      />
      <el-table-column
        align="center"
        label="节数"
        min-width="120"
        prop="classNumber"
      />
      <el-table-column
        align="center"
        label="周数"
        min-width="120"
        prop="weekNumber"
      />
      <el-table-column
        align="center"
        label="星期几"
        min-width="120"
        prop="dayOfWeek"
      />
      <el-table-column
        align="center"
        label="创建时间"
        min-width="180"
        prop="createTime"
      />
      <el-table-column align="center" fixed="right" label="操作" width="300">
        <template #default="scope">
          <el-button
            type="primary"
            link
            icon="edit"
            @click="openEditDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :icon="InfoFilled"
            icon-color="#626AEF"
            width="180"
            title="是否删除该安排?"
            @confirm="deleteScheduleById(scope.row.scheduleId)"
          >
            <template #reference>
              <el-button type="primary" link icon="delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 12px"
      v-model:current-page="schedulePageParmas.pageNum"
      v-model:page-size="schedulePageParmas.pageSize"
      :page-sizes="[10, 20, 40]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      v-model="dialogFormVisible"
      :title="dialogTitle"
      style="min-width: 320px"
    >
      <el-form
        v-if="dialogFormVisible"
        ref="scheduleForms"
        :inline="true"
        :model="scheduleForm"
        :rules="rules"
        label-position="top"
        label-width="85px"
      >
        <el-form-item label="课程ID" prop="courseId" style="width: 40%">
          <el-input
            v-model="scheduleForm.courseId"
            placeholder="请输入课程ID"
          />
        </el-form-item>
        <el-form-item label="教室" prop="classroom" style="width: 40%">
          <el-input v-model="scheduleForm.classroom" placeholder="请输入教室" />
        </el-form-item>
        <el-form-item label="上课次数" prop="lessonNumber" style="width: 40%">
          <el-input-number v-model="scheduleForm.lessonNumber" />
        </el-form-item>
        <el-form-item label="节数" prop="classNumber" style="width: 40%">
          <el-input-number v-model="scheduleForm.classNumber" />
        </el-form-item>
        <el-form-item label="周数" prop="weekNumber" style="width: 40%">
          <el-input-number v-model="scheduleForm.weekNumber" />
        </el-form-item>
        <el-form-item label="星期几" prop="dayOfWeek" style="width: 40%">
          <el-input
            v-model="scheduleForm.dayOfWeek"
            placeholder="请输入星期几"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="formConfirm(scheduleForms)">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import {
  reqAddSchedule,
  reqDeleteScheduleById,
  reqGetAllScheduleByAdmin,
  reqUpdateSchedule,
} from '@/api/schedule'
import {
  SchedulePageQuery,
  ScheduleParams,
  ScheduleType,
} from '@/api/schedule/type'

onMounted(async () => {
  await getScheduleInfoPage()
})

const dialogFormVisible = ref<boolean>(false)
const schedulePageParmas: SchedulePageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
})
const scheduleDatas = ref<ScheduleType[]>()
const total = ref(0)
const loading = ref(false)

const scheduleForms = ref<FormInstance>()
let scheduleForm: ScheduleParams = reactive({
  scheduleId: 0,
  courseId: 0,
  lessonNumber: 0,
  classNumber: 0,
  weekNumber: 0,
  dayOfWeek: '',
  classroom: '',
})

const rules = reactive({
  lessonNumber: [{ required: true, message: '请输入次数', trigger: 'blur' }],
  courseId: [{ required: true, message: '请选择课程', trigger: 'blur' }],
  classNumber: [{ required: true, message: '请输入节数', trigger: 'blur' }],
  weekNumber: [{ required: true, message: '请输入周数', trigger: 'blur' }],
  dayOfWeek: [{ required: true, message: '请输入星期几', trigger: 'blur' }],
  classroom: [{ required: true, message: '请输入教室', trigger: 'blur' }],
})

// 添加菜单方法，id为 0则为添加根菜单
const dialogTitle = ref('新增安排')
const isEdit = ref(false)

const getScheduleInfoPage = async () => {
  loading.value = true
  try {
    const { data } = await reqGetAllScheduleByAdmin(schedulePageParmas)
    scheduleDatas.value = data.list
    total.value = data.total
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false
  }
}

const indexMethod = (index: number) => {
  return (
    index + (schedulePageParmas.pageNum - 1) * schedulePageParmas.pageSize + 1
  )
}

const deleteScheduleById = async (id: number) => {
  try {
    const { message } = await reqDeleteScheduleById(id)
    ElMessage.success(message)
    await getScheduleInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const addSchedule = async () => {
  try {
    const { message } = await reqAddSchedule(scheduleForm)
    ElMessage.success(message)
    scheduleForm = {
      scheduleId: 0,
      courseId: 0,
      lessonNumber: 0,
      classNumber: 0,
      weekNumber: 0,
      dayOfWeek: '',
      classroom: '',
    }
    await getScheduleInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const updateSchedule = async () => {
  try {
    const { message } = await reqUpdateSchedule(scheduleForm)
    ElMessage.success(message)
    await getScheduleInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const formConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        updateSchedule()
      } else {
        addSchedule()
      }
      dialogFormVisible.value = false
    }
  })
}

const openAddDialog = () => {
  isEdit.value = false
  if (scheduleForm.scheduleId !== 0) {
    scheduleForm = {
      scheduleId: 0,
      courseId: 0,
      lessonNumber: 0,
      classNumber: 0,
      weekNumber: 0,
      dayOfWeek: '',
      classroom: '',
    }
  }
  dialogTitle.value = '新增安排'
  dialogFormVisible.value = true
}
// 修改菜单方法
const openEditDialog = async (data: ScheduleType) => {
  isEdit.value = true
  dialogTitle.value = '编辑安排'
  scheduleForm.scheduleId = data.scheduleId
  scheduleForm.courseId = data.courseId
  scheduleForm.lessonNumber = data.lessonNumber
  scheduleForm.classNumber = data.classNumber
  scheduleForm.weekNumber = data.weekNumber
  scheduleForm.dayOfWeek = data.dayOfWeek
  scheduleForm.classroom = data.classroom
  dialogFormVisible.value = true
}

const handleSizeChange = (val: number) => {
  getScheduleInfoPage()
}
const handleCurrentChange = (val: number) => {
  getScheduleInfoPage()
}
</script>
<style scoped lang="scss">
.schedule_box {
  padding: 24px;

  .schedule_addbtn {
    margin-bottom: 12px;
    display: flex;
  }
}
</style>
